package com.shop.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.dto.AdminCost.*;
import com.shop.entity.dto.AdminStyle.AdminStyleCostDto;
import com.shop.entity.dto.AdminWares.*;
import com.shop.entity.pojo.*;
import com.shop.admin.mapper.AdminUserMapper;
import com.shop.admin.mapper.CostMapper;
import com.shop.admin.mapper.StyleMapper;
import com.shop.admin.mapper.WaresMapper;
import com.shop.admin.service.CostService;
import com.shop.utils.common.enums.Code;
import com.shop.utils.common.enums.Message;
import com.shop.utils.common.result.PageResponseResult;
import com.shop.utils.common.result.Result;
import com.shop.utils.config.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class CostServiceImpl extends ServiceImpl<CostMapper, Cost> implements CostService {

    @Autowired
    private CostMapper costMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;
    @Override
    public Result saveOneCost(AdminCostSaveDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-添加单个价格");
        if (dto==null) {
            log.info("dto==null");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminUser==null||adminId==null) {
            log.info("无法查询到该管理员");
            Result.errorResult(Code.PARAM_INVALID);
        }
        List<Cost> costList = costMapper.selectList(Wrappers.<Cost>lambdaQuery().eq(Cost::getWaresId, dto.getWaresId()).eq(Cost::getStyleId, dto.getStyleId()).eq(Cost::getCostMessage, dto.getCostMessage()).eq(Cost::getWaresPrice, dto.getCostPrice()));
        if (!CollectionUtils.isEmpty(costList)||costList.size()>Message.Check_Int_Null) {
            log.info("该商品的价格存在相同,costList:{}",costList);
            return Result.errorResult(Code.DATA_EXIST);
        }
        log.info("添加商品价格");
        Cost cost=new Cost();
        cost= cost.builder()
                .waresId(dto.getWaresId())
                .styleId(dto.getStyleId())
                .costMessage(dto.getCostMessage())
                .waresPrice(dto.getCostPrice())
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        boolean save = save(cost);
        if (!save) {
            log.info("添加失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理添加单个价格进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Result<List<Cost>> getWaresCost(AdminWaresCostListDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-查看商品相关价格套餐");
        if (dto==null||dto.getWaresId()!=null) {
            log.info("未接收到传递的参数");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        dto.checkParam();
        Page<Cost> page=new Page<>(dto.getPage(),dto.getSize());
        String key=Message.Admin_key_Wares_Cost+dto.getWaresId();
        Page<Cost> check = (Page<Cost>) redisTemplate.opsForValue().get(key);
        if (check!=null&&!check.equals("")) {
            log.info("浏览缓存");
            Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) check.getTotal());
            result.setData(check.getRecords());
            long end = System.currentTimeMillis();
            log.info("后台管理查看商品相关价格套餐进程完成，总耗时:{}",(end-start));
            return result;
        }
        log.info("浏览数据库");
        Page<Cost> value = costMapper.getByWaresId(page, dto.getWaresId());
        redisTemplate.opsForValue().set(key,value);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) value.getTotal());
        result.setData(value.getRecords());
        long end = System.currentTimeMillis();
        log.info("后台管理查看商品相关价格套餐进程完成，总耗时:{}",(end-start));
        return result;
    }

    @Autowired
    private StyleMapper styleMapper;
    @Autowired
    private WaresMapper waresMapper;
    @Override
    public Result updateCost(AdminCostUpdateDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-修改商品价格");
        if (dto==null||dto.getCostId()==null) {
            log.info("未接收到前端传来的参数");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectOne(Wrappers.<AdminUser>lambdaQuery().eq(AdminUser::getId, adminId));
        if (adminUser==null||adminId==null) {
            log.info("未查询到该管理员的信息");
            return Result.errorResult(Code.PARAM_INVALID);
        }
        Cost oldCost = getOne(Wrappers.<Cost>lambdaQuery().eq(Cost::getId, dto.getCostId()));
        if (oldCost==null) {
            log.info("未查询到需要修改的价格");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Long waresId=oldCost.getWaresId();
        if (dto.getWaresId()!=null) {
            log.info("更新新的价格归属商品");
            Wares wares = waresMapper.selectById(dto.getWaresId());
            if (wares==null) {
                log.info("未找到需要更新归属的商品");
                return Result.errorResult(Code.DATA_NOT_EXIST);
            }
            waresId=wares.getId();
        }
        Long styleId=oldCost.getStyleId();
        if (dto.getStyleId()!=null) {
            log.info("更新新的价格归属款式");
            Style style = styleMapper.selectById(dto.getStyleId());
            if (style==null) {
                log.info("未查询到要选择的款式");
                return Result.errorResult(Code.DATA_NOT_EXIST);
            }
            styleId=style.getId();
        }
        String costMessage=oldCost.getCostMessage();
        if (dto.getCostMessage()!=null) {
            log.info("更新新的价格信息");
            List<Cost> message = costMapper.selectList(Wrappers.<Cost>lambdaQuery()
                    .eq(Cost::getCostMessage, dto.getCostMessage())
                    .eq(Cost::getWaresId,waresId)
                    .eq(Cost::getStyleId,styleId));
            if (!CollectionUtils.isEmpty(message)||message.size()>Message.Check_Int_Null) {
                log.info("该该商品的价格信息已存在");
                return Result.errorResult(Code.DATA_EXIST);
            }
            costMessage= dto.getCostMessage();
        }
        double waresPrice=oldCost.getWaresPrice();
        if (dto.getWaresPrice()!=Message.Check_Int_Null) {
            log.info("更新新的价格");
            List<Cost> price = costMapper.selectList(Wrappers.<Cost>lambdaQuery()
                    .eq(Cost::getWaresPrice, dto.getWaresPrice())
                    .eq(Cost::getCostMessage, dto.getCostMessage())
                    .eq(Cost::getWaresId,waresId)
                    .eq(Cost::getStyleId,styleId));
            if (!CollectionUtils.isEmpty(price)||price.size()>Message.Check_Int_Null) {
                log.info("该商品的价格已存在");
                return Result.errorResult(Code.DATA_EXIST);
            }
            waresPrice=dto.getWaresPrice();
        }

        Cost cost=new Cost();
        cost=cost.builder()
                .styleId(styleId)
                .waresId(waresId)
                .costMessage(costMessage)
                .waresPrice(waresPrice)
                .saveAdmin(adminUser.getName()).build();
        boolean update = update(cost, Wrappers.<Cost>lambdaUpdate().eq(Cost::getId, dto.getCostId()));
        if (!update) {
            log.info("修改失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理修改商品价格进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result removeCost(AdminCostRemoveDto dto) {
        long start = System.currentTimeMillis();
        log.info("删除商品价格");
        if (dto==null||dto.getCostId()==null||dto.getRemoveMemo()==null) {
            log.info("未接收到前端传来的数据");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminId==null||adminUser==null) {
            log.info("未查询到该管理员");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Cost cost = costMapper.selectById(dto.getCostId());
        if (cost==null) {
            log.info("未查询到需要删除的商品价格");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Cost newCost=new Cost();
        newCost= newCost.builder()
                .removeMemo(dto.getRemoveMemo())
                .removeAdmin(adminUser.getName()).build();
        boolean update = update(newCost, Wrappers.<Cost>lambdaUpdate().eq(Cost::getId, dto.getCostId()));
        if (!update) {
            log.info("修改失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        int delCost = costMapper.deleteById(dto.getCostId());
        if (delCost==Message.Check_Int_False) {
            log.info("删除失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理删除商品价格进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result<Cost> updateGetCost(AdminCostUpdateForGetDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-修改商品价格数据回显");
        if (dto.getCostId()==null) {
            log.info("未接收到前端传来的价格ID");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Cost cost = getOne(Wrappers.<Cost>lambdaQuery().eq(Cost::getId, dto.getCostId()));
        if (cost==null) {
            log.info("未查询到该商品价格");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理修改商品价格数据回显进程完成，总耗时:{}",(end-start));
        return Result.okResult(cost);
    }

    @Override
    public Result getCostList(AdminCostListDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-价格列表");
        dto.checkParam();
        Page<Cost> page=new Page<>(dto.getPage(),dto.getSize());
        String key=Message.Admin_key_Cost_All;
        Page<Cost> check = (Page<Cost>) redisTemplate.opsForValue().get(key);
        if (check!=null&&!check.equals("")) {
            log.info("浏览缓存");
            Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) check.getTotal());
            result.setData(check.getRecords());
            long end = System.currentTimeMillis();
            log.info("后台管理商品价格列表进程完成，总耗时:{}",(end-start));
            return result;
        }
        log.info("浏览数据库");
        Page<Cost> value = costMapper.getAllByPage(page, dto);
        redisTemplate.opsForValue().set(key,value);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) value.getTotal());
        result.setData(value.getRecords());
        long end = System.currentTimeMillis();
        log.info("后台管理商品价格列表进程完成，总耗时:{}",(end-start));
        return result;
    }

    @Override
    public Result openCost(AdminCostOpenDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-恢复商品价格");
        if ( dto.getCostId()==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        Cost byId = costMapper.getOne(dto.getCostId());
        if (adminId==null||adminUser==null||byId==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        if (byId.getIsDelete()==Message.Delete_False) {
            return Result.errorResult(Code.PARAM_INVALID);
        }
        Cost cost=new Cost();
        cost=cost.builder()
                .id(dto.getCostId())
                .removeAdmin(null)
                .removeMemo(null)
                .isDelete(Message.Put)
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        boolean update = costMapper.updateIsDelete(cost);
        if (!update) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理恢复商品价格进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result getStyleCostByPage(AdminStyleCostDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-商品款式相关价格");
        if (dto.getStyleId()==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        dto.checkParam();
        Page<Cost> page=new Page<>(dto.getPage(),dto.getSize());
        String key=Message.Admin_key_Style_Cost+dto.getStyleId();
        Page<Style> check = (Page<Style>) redisTemplate.opsForValue().get(key);
        if (check!=null&&!check.equals("")) {
            log.info("浏览缓存");
            Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) check.getTotal());
            result.setData(check.getRecords());
            long end = System.currentTimeMillis();
            log.info("后台管理商品款式相关价格进程完成，总耗时:{}",(end-start));
            return result;
        }
        Page<Cost> value = costMapper.CostPageByStyleId(page, dto);
        redisTemplate.opsForValue().set(key,value);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) value.getTotal());
        result.setData(value.getRecords());
        long end = System.currentTimeMillis();
        log.info("后台管理商品款式相关价格进程完成，总耗时:{}",(end-start));
        return result;
    }

    @Override
    public Result pullCost(AdminCostPullDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-下架商品价格");
        if (dto.getCostId()==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminUser==null||adminId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Style style=new Style();
        Cost cost=new Cost();
        Cost checkCost = costMapper.selectById(dto.getCostId());
        if (checkCost==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        cost= cost.builder().state(Message.Pull).removeAdmin(adminUser.getName()).removeMemo(dto.getMemo()).build();
        style.setState(Message.Exception);
        int pullCost = costMapper.update(cost, Wrappers.<Cost>lambdaUpdate().eq(Cost::getId, dto.getCostId()));
        if (pullCost==Message.Check_Int_False) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理下架商品价格进程完成，总耗时:{}",(end-start));
        return Result.errorResult(Code.SUCCESS);
    }

    @Override
    public Result putCost(AdminCostPutDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-上架商品价格");
        if (dto.getCostId()==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminUser==null||adminId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Cost cost=new Cost();
        Cost checkCost = costMapper.selectById(dto.getCostId());
        if (checkCost==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        cost= cost.builder().state(Message.Put).saveAdmin(adminUser.getName()).saveTime(String.valueOf(LocalDateTime.now())).build();
        int pullCost = costMapper.update(cost, Wrappers.<Cost>lambdaUpdate().eq(Cost::getId, dto.getCostId()));
        if (pullCost==Message.Check_Int_False) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理上架商品价格进程完成，总耗时:{}",(end-start));
        return Result.errorResult(Code.SUCCESS);
    }

}
